﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace JWTMiddre.Middleware
{
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;
      
        public JwtMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var token = context.Request.Headers["Authorization"].FirstOrDefault();
            if (token != null)
                AttachUserToContext(context, token);

            await _next(context);
        }
        private void AttachUserToContext(HttpContext context, string token)
        {

            try
            {
                var tokenHandler = new AuthorizationHandler();
                var validate = tokenHandler.ValidateClientAuthentication(token);
                if (validate)
                {
                    var user = fastJSON.JSON.ToObject<AuthenUser>(Base64Decode(token.Split(".")[1]));
                    context.Items["user"] = user;
                }
                else
                {
                    context.Items["user"] = null;
                }
                
            }
            catch
            {

                // do nothing if jwt validation fails
                // user is not attached to context so request won't have access to secure routes
            }
        }
        private string Base64Decode(string Message)
        {
            byte[] bytes = Convert.FromBase64String(Message);
            return Encoding.Default.GetString(bytes);
        }
        public class AuthenUser
        {

            public string name { get; set;  }

            public string sex { get; set; }
        }
    }
}
